from django.http import JsonResponse
from drf_spectacular.utils import extend_schema
from rest_framework.decorators import action
from rest_framework.mixins import (CreateModelMixin, ListModelMixin,
                                   RetrieveModelMixin, UpdateModelMixin)
from rest_framework.viewsets import GenericViewSet
from utils.autoschema import AutoDocSchema, custom_response_serailizer
from utils.decorators import error_response, request_data
from backend.cews.models import PartsEDoc
from django_filters import rest_framework as filters
from .serializers import (PartsEDocSerializer)
from rest_framework.response import Response

import django_filters


class CustomFilter(filters.FilterSet):
    # parts = filters.Filter(field_name='parts', lookup_expr='exact')
    class Meta:
        model = PartsEDoc
        fields = ['doc_name','parts','invalid']
        

class PartsEDocViewSet(
    RetrieveModelMixin,
    ListModelMixin,
    UpdateModelMixin,
    GenericViewSet,
    CreateModelMixin
):
    serializer_class = PartsEDocSerializer
    queryset = PartsEDoc.objects.all().filter(deleted=False)
    filterset_class = CustomFilter
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
    
    @error_response()
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["part_ids","invalid"])
    def listChildPartsEdocs(self, request, part_ids,invalid):

        print(part_ids)
        results = self.queryset.filter(parts_id__in=part_ids,invalid=invalid)

        # if results:
        data = PartsEDocSerializer(results, many=True).data
        return Response(status=200,
                        data={
                            'code': 1,
                            'data': data
                        })
